﻿using log4net;
using Mangox.Common;
using Mangox.Model.MangoxDB;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Mangox.BLL.Applet
{
    public class UserSignBLL
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";


        /// <summary>
        /// 获取最新一条签到
        /// 再换算出金币
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public UserSign GetUserSign(int userid)
        {
            UserSign model = null;

            try
            {
                using (MangoxDBEntities db = new MangoxDBEntities())
                {
                    //必须是主键，否则会报错
                    //model = dbContext.UserSigns.Find(id);

                    //DateTime dtime = DateTime.Now.Date;
                    //&& u.LastModifyTime > dtime

                    var obj = db.UserSigns.Where(t => true);
                    obj = obj.Where(u => u.UserID == userid);
                    obj = obj.OrderByDescending(u => u.LastModifyTime);
                    obj = obj.Take(1);

                    var tempList = obj.ToList();
                    if (tempList != null && tempList.Count > 0)
                    {
                        model = tempList[0];
                        model.Count = model.Count ?? 0;
                        model.SignCount = model.SignCount ?? 0;
                        //金币等于签到次数乘以10，连续签到未计算
                        model.Integral = model.Count * 10;
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"获取签到异常 userid-{userid} fail-{ex.ToString()}");
            }
            return model;
        }

        /// <summary>
        /// 添加签到，如果用户不是第一次签到，就+1
        /// 更新，查询出时间最大的id
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public UserSign SignIn(UserSign model)
        {
            bool flag = false;
            UserSign ret = new UserSign();
            try
            {
                log.Info($"添加签到 model-{JsonCommon.ToJson<UserSign>(model)}");

                if (model.UserID <= 0)
                {
                    return null;
                }

                using (MangoxDBEntities db = new MangoxDBEntities())
                {
                    UserSign sign = null;

                    var obj = db.UserSigns.Where(t => true);
                    obj = obj.Where(u => u.UserID == model.UserID);
                    obj = obj.OrderByDescending(u => u.LastModifyTime);
                    obj = obj.Take(1);

                    var tempList = obj.ToList();
                    if (tempList != null && tempList.Count > 0)
                    {
                        sign = tempList[0];
                    }
                    
                    //sign.Count = sign.Count ?? 0;
                    var count = 0;
                    if (sign != null)
                    {
                        //已经签到则跳出
                        if (Convert.ToDateTime(sign.LastModifyTime).Date == DateTime.Now.Date)
                        {
                            log.Info($"今日已签到 UserID-{model.UserID}");
                            return sign;
                        }

                        count = (int)sign.Count + 1;
                    }
                    else
                    {
                        count = 1;
                    }

                    var temp = new UserSign()
                    {
                        Openid = model.Openid,
                        UserID = model.UserID,
                        UID = model.UID,
                        Count = count,
                        //SignCount = 1, //连续签到暂时未计算
                        LastModifyTime = DateTime.Now,
                        Integral = count * 10
                    };
                    ret = temp;
                    db.UserSigns.Add(temp);

                    flag = db.SaveChanges() > 0;
                    log.Info(className + $"签到 flag-{flag.ToString()}");
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"添加签到异常 fail-{ex.ToString()}");
            }
            return ret;
        }


    }
}
